package com.xyht.sca_s.student_manage_system.modules.walkThrough.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgStructure;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgUserRelation;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgUserRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsStudentInfo;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsUserStudentRelation;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsStudentInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsUserStudentRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUserRoleRelation;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserRoleRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.walkThrough.entity.SmsWalkThrough;
import com.xyht.sca_s.student_manage_system.modules.walkThrough.entity.SmsWalkThroughDetail;
import com.xyht.sca_s.student_manage_system.modules.walkThrough.entity.dto.SmsWalkThroughAddDto;
import com.xyht.sca_s.student_manage_system.modules.walkThrough.entity.dto.SmsWalkThroughApprovalDto;
import com.xyht.sca_s.student_manage_system.modules.walkThrough.entity.vo.SmsWalkThroughAuditListVo;
import com.xyht.sca_s.student_manage_system.modules.walkThrough.entity.vo.SmsWalkThroughDetailVo;
import com.xyht.sca_s.student_manage_system.modules.walkThrough.entity.vo.SmsWalkThroughVo;
import com.xyht.sca_s.student_manage_system.modules.walkThrough.mapper.SmsWalkThroughDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.walkThrough.mapper.SmsWalkThroughMapper;
import com.xyht.sca_s.student_manage_system.modules.walkThrough.service.SmsWalkThroughService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.org.constants.OrgTypeConstant.ORG_TYPE_CLASS;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.RoleIDConstant.ROLE_STUDENT_ID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-02-12
 */
@Service
public class SmsWalkThroughServiceImpl extends ServiceImpl<SmsWalkThroughMapper, SmsWalkThrough> implements SmsWalkThroughService {

    @Autowired
    private SmsUserRoleRelationMapper smsUserRoleRelationMapper;
    @Autowired
    private SmsUserMapper smsUserMapper;
    @Autowired
    private SmsWalkThroughDetailMapper smsWalkThroughDetailMapper;
    @Autowired
    private SmsUserStudentRelationMapper smsUserStudentRelationMapper;
    @Autowired
    private SmsStudentInfoMapper smsStudentInfoMapper;
    @Autowired
    private SmsOrgUserRelationMapper smsOrgUserRelationMapper;
    @Autowired
    private SmsOrgStructureMapper smsOrgStructureMapper;
    @Autowired
    private SmsWalkThroughMapper smsWalkThroughMapper;
    @Override
    public ResponseResult addWalkThrough(SmsWalkThroughAddDto smsWalkThroughAddDto, String userId) {
        //校验参数
        if (isNullOrEmpty(smsWalkThroughAddDto.getStuName()) || isNullOrEmpty(smsWalkThroughAddDto.getSex())
                || isNullOrEmpty(smsWalkThroughAddDto.getStuNation()) || isNullOrEmpty(smsWalkThroughAddDto.getStuMajor())
                || isNullOrEmpty(smsWalkThroughAddDto.getTelephone()) || isNullOrEmpty(smsWalkThroughAddDto.getStuPhone())
                || isNullOrEmpty(smsWalkThroughAddDto.getBirthPlace()) || isNullOrEmpty(smsWalkThroughAddDto.getAddress())
                || isNullOrEmpty(smsWalkThroughAddDto.getKeyWorker()) || isNullOrEmpty(smsWalkThroughAddDto.getWorkerPhone())
                || isNullOrEmpty(smsWalkThroughAddDto.getWalkTime()) || isNullOrEmpty(smsWalkThroughAddDto.getComeTime())
                || isNullOrEmpty(smsWalkThroughAddDto.getWalkReasons())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsWalkThrough smsWalkThrough = new SmsWalkThrough();
        //赋值
        BeanUtils.copyProperties(smsWalkThroughAddDto, smsWalkThrough);
        //查看是否已在申请走读
        QueryWrapper<SmsWalkThrough> walkThroughQueryWrapper = new QueryWrapper<>();
        walkThroughQueryWrapper.lambda().eq(SmsWalkThrough::getUserId,userId)
                .eq(SmsWalkThrough::getAuditStatus,"0");
        List<SmsWalkThrough> result = smsWalkThroughMapper.selectList(walkThroughQueryWrapper);
        if(result != null && result.size() > 0){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //用户角色校验
        QueryWrapper<SmsUserRoleRelation> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(SmsUserRoleRelation::getUserId, userId)
                .eq(SmsUserRoleRelation::getRoleId, ROLE_STUDENT_ID);
        SmsUserRoleRelation adminRole = smsUserRoleRelationMapper.selectOne(queryWrapper);
        if (adminRole == null) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //用户信息校验
        QueryWrapper<SmsUserStudentRelation> userStudentRelationQueryWrapper = new QueryWrapper<>();
        userStudentRelationQueryWrapper.lambda().eq(SmsUserStudentRelation::getUserId, userId);
        SmsUserStudentRelation userStudentRelation = smsUserStudentRelationMapper.selectOne(userStudentRelationQueryWrapper);
        if (userStudentRelation == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_STUDENT_INFO);
        }
        SmsStudentInfo smsStudentInfo = smsStudentInfoMapper.selectById(userStudentRelation.getStuId());
        if (smsStudentInfo == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_STUDENT_INFO);
        }

        //用户组织班级校验
        QueryWrapper<SmsOrgUserRelation> orgUserRelationQueryWrapper = new QueryWrapper<>();
        orgUserRelationQueryWrapper.lambda().eq(SmsOrgUserRelation::getUserId, userId);
        List<SmsOrgUserRelation> orgUserRelationList = smsOrgUserRelationMapper.selectList(orgUserRelationQueryWrapper);
        if (orgUserRelationList == null || orgUserRelationList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_ORG_INFO);
        }
        List<String> orgIDList = orgUserRelationList.stream().map(SmsOrgUserRelation::getOrgId).collect(Collectors.toList());
        QueryWrapper<SmsOrgStructure> orgStructureQueryWrapper = new QueryWrapper<>();
        orgStructureQueryWrapper.lambda().in(SmsOrgStructure::getId, orgIDList).eq(SmsOrgStructure::getLevel, ORG_TYPE_CLASS);
        List<SmsOrgStructure> orgStructureList = smsOrgStructureMapper.selectList(orgStructureQueryWrapper);
        if (orgStructureList == null || orgStructureList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_ORG_INFO);
        }
        Integer stuClassOrgId = orgStructureList.get(0).getId();
        //走读申请保存
        smsWalkThrough.setStuNo(smsStudentInfo.getStuNo());
        smsWalkThrough.setUserId(userId);
        smsWalkThrough.setStuId(userStudentRelation.getStuId());
        smsWalkThrough.setStuClass(stuClassOrgId.toString());//班级
        smsWalkThrough.setApplicationTime(new Date());//申请时间
        smsWalkThrough.setCreatTime(new Date());
        smsWalkThrough.setStuEnterDate(smsStudentInfo.getStuEnterDate());//入学年月
        smsWalkThrough.setStuCard(smsStudentInfo.getStuIdCard());//身份证
        smsWalkThrough.setStuCollage(smsStudentInfo.getStuCollege());//学院
        smsWalkThroughMapper.insert(smsWalkThrough);
        if (isNullOrEmpty(smsWalkThrough.getId())) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }

        //保存审核流程
        SmsWalkThroughDetail smsWalkThroughDetail = new SmsWalkThroughDetail();
        smsWalkThroughDetail.setWalkThroughId(smsWalkThrough.getId());
        smsWalkThroughDetail.setCreateTime(new Date());
        smsWalkThroughDetailMapper.insert(smsWalkThroughDetail);
        return CommonResult.success();
    }

    @Override
    public ResponseResult selectWalkThroughList(Integer pageSize, Integer pageNum,String userId) {
        Page<SmsWalkThrough> page = new Page<>(pageNum, pageSize);
        //查数据库中的数据
        QueryWrapper<SmsWalkThrough> walkThroughQueryWrapper = new QueryWrapper<>();
        walkThroughQueryWrapper.lambda().eq(SmsWalkThrough::getUserId, userId)
                .orderByDesc(SmsWalkThrough::getApplicationTime);
        smsWalkThroughMapper.selectPage(page,walkThroughQueryWrapper);
        //赋值
        List<SmsWalkThroughVo> smsWalkThroughVos = new ArrayList<>();
        int total = (int) page.getTotal();
        List<SmsWalkThrough> list = page.getRecords();
        if(list != null && list.size()>0) {
            for (SmsWalkThrough smsWalkThrough : list) {
                SmsWalkThroughVo smsWalkThroughVo = new SmsWalkThroughVo();
                QueryWrapper<SmsWalkThroughDetail> smsWalkThroughDetailQueryWrapper = new QueryWrapper<>();
                smsWalkThroughDetailQueryWrapper.lambda().eq(SmsWalkThroughDetail::getWalkThroughId,smsWalkThrough.getId());
                SmsWalkThroughDetail smsWalkThroughDetail = smsWalkThroughDetailMapper.selectOne(smsWalkThroughDetailQueryWrapper);
                smsWalkThroughVo.setId(smsWalkThrough.getId());
                smsWalkThroughVo.setStuName(smsWalkThrough.getStuName());
                smsWalkThroughVo.setWalkReasons(smsWalkThrough.getWalkReasons());
                smsWalkThroughVo.setApprovalTime(smsWalkThroughDetail.getAuditTime());
                smsWalkThroughVo.setAuditStatus(smsWalkThrough.getAuditStatus());
                smsWalkThroughVo.setApplicationTime(smsWalkThrough.getApplicationTime());
                smsWalkThroughVo.setAuditor(smsWalkThroughDetail.getRoleName());
                smsWalkThroughVos.add(smsWalkThroughVo);
            }
        }
        return CommonResult.success(smsWalkThroughVos,total);
    }

    @Override
    public ResponseResult selectWalkThroughById(String id) {
        //判断参数
        if(isNullOrEmpty(id)){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //查询是否有申请数据
        SmsWalkThrough smsWalkThrough = smsWalkThroughMapper.selectById(id);
        if(smsWalkThrough == null){
            return CommonResult.failed(CommonCodeEnum.WALK_THOUGH_NOT_EXIST);
        }
        SmsWalkThroughDetailVo smsWalkThroughDetailVo = new SmsWalkThroughDetailVo();
        BeanUtils.copyProperties(smsWalkThrough, smsWalkThroughDetailVo);
        QueryWrapper<SmsWalkThroughDetail> smsWalkThroughDetailQueryWrapper = new QueryWrapper<>();
        smsWalkThroughDetailQueryWrapper.lambda().eq(SmsWalkThroughDetail::getWalkThroughId,smsWalkThrough.getId());
        SmsWalkThroughDetail smsWalkThroughDetail = smsWalkThroughDetailMapper.selectOne(smsWalkThroughDetailQueryWrapper);
        smsWalkThroughDetailVo.setAuditor(smsWalkThroughDetail.getRoleName());
        smsWalkThroughDetailVo.setApprovalTime(smsWalkThroughDetail.getAuditTime());
        return CommonResult.success(smsWalkThroughDetailVo);
    }

    @Override
    public ResponseResult selectStudentWalkThrough(Integer pageSize, Integer pageNum, String userId, String content) {
        Page<SmsWalkThrough> page = new Page<>(pageNum, pageSize);
        //查数据库中的数据
        QueryWrapper<SmsWalkThrough> walkThroughQueryWrapper = new QueryWrapper<>();

        //模糊查询通过事由和走读申请时间
        walkThroughQueryWrapper.like(StringUtils.isNotBlank(content),"walk_reasons",content)
                .or().like(StringUtils.isNotBlank(content),"audit_status",content);
        walkThroughQueryWrapper.lambda().eq(SmsWalkThrough::getUserId,userId)
                .orderByDesc(SmsWalkThrough::getApplicationTime);
        smsWalkThroughMapper.selectPage(page,walkThroughQueryWrapper);
        List<SmsWalkThrough> list = page.getRecords();
        if(list == null){
            return CommonResult.failed(CommonCodeEnum.WALK_THOUGH_NOT_EXIST);
        }
        List<SmsWalkThroughVo> smsWalkThroughVos = new ArrayList<>();
        for (SmsWalkThrough smsWalkThrough : list) {
            SmsWalkThroughVo smsWalkThroughVo = new SmsWalkThroughVo();
            BeanUtils.copyProperties(smsWalkThrough, smsWalkThroughVo);
            smsWalkThroughVos.add(smsWalkThroughVo);
        }
        int total = (int) page.getTotal();
        return CommonResult.success(smsWalkThroughVos,total);
    }

    @Override
    public ResponseResult approvalWalkThrough(SmsWalkThroughApprovalDto smsWalkThroughApprovalDto, String userId) {
        if (isNullOrEmpty(smsWalkThroughApprovalDto.getWalkThroughId()) || isNullOrEmpty(smsWalkThroughApprovalDto.getDetailId())
            || isNullOrEmpty(smsWalkThroughApprovalDto.getAuditStatus())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //查询走读审核流程是否有
        QueryWrapper<SmsWalkThroughDetail> smsWalkThroughDetailQueryWrapper = new QueryWrapper<>();
        smsWalkThroughDetailQueryWrapper.lambda().eq(SmsWalkThroughDetail::getAuditStatus,"0")
                .eq(SmsWalkThroughDetail::getId,smsWalkThroughApprovalDto.getDetailId());
        SmsWalkThroughDetail smsWalkThroughDetails = smsWalkThroughDetailMapper.selectOne(smsWalkThroughDetailQueryWrapper);
        //不存在审核,该申请已被审批，请刷新界面
        if(smsWalkThroughDetails == null){
            return CommonResult.failed(CommonCodeEnum.LEAVE_ALLOWED);
        }

        //查走读申请
        QueryWrapper<SmsWalkThrough> smsWalkThroughQueryWrapper = new QueryWrapper<>();
        smsWalkThroughQueryWrapper.lambda().eq(SmsWalkThrough::getAuditStatus,"0")
                .eq(SmsWalkThrough::getId,smsWalkThroughApprovalDto.getWalkThroughId());
        SmsWalkThrough smsWalkThrough = smsWalkThroughMapper.selectOne(smsWalkThroughQueryWrapper);
        //不存在走读申请,该申请已被审批，请刷新界面
        if (smsWalkThrough == null){
            return CommonResult.failed(CommonCodeEnum.LEAVE_ALLOWED);
        }
        QueryWrapper<SmsUserRoleRelation> smsUserRoleRelationQueryWrapper = new QueryWrapper<>();
        smsUserRoleRelationQueryWrapper.lambda().eq(SmsUserRoleRelation::getUserId,userId);
        List<SmsUserRoleRelation> smsUserRoleRelation = smsUserRoleRelationMapper.selectList(smsUserRoleRelationQueryWrapper);
        List<String> roleIds = new ArrayList<>();
        for (SmsUserRoleRelation userRoleRelation : smsUserRoleRelation) {
            String roleId = userRoleRelation.getRoleId();
            roleIds.add(roleId);
        }
        //判断是否是辅导员
        if(!roleIds.contains("4")){
            return CommonResult.failed(CommonCodeEnum.LEAVE_ALLOW_NOT_OWN_CLASS);
        }
        SmsWalkThroughDetail smsWalkThroughDetail = new SmsWalkThroughDetail();
        smsWalkThroughDetail.setId(smsWalkThroughApprovalDto.getDetailId());
        smsWalkThroughDetail.setAuditStatus(smsWalkThroughApprovalDto.getAuditStatus());
        smsWalkThroughDetail.setAuditTime(new Date());
        SmsUser smsUser = smsUserMapper.selectById(userId);
        smsWalkThroughDetail.setRoleName(smsUser.getRealName());
        smsWalkThroughDetailMapper.updateById(smsWalkThroughDetail);
        SmsWalkThrough smsWalkThrough1 = new SmsWalkThrough();
        smsWalkThrough1.setAuditStatus(smsWalkThroughApprovalDto.getAuditStatus());
        smsWalkThrough1.setId(smsWalkThroughApprovalDto.getWalkThroughId());
        smsWalkThroughMapper.updateById(smsWalkThrough1);
        return CommonResult.success();
    }

    @Override
    public ResponseResult selectAuditList(Integer pageSize, Integer pageNum,String userId) {
        //先判断是否是辅导员
        QueryWrapper<SmsUserRoleRelation> smsUserRoleRelationQueryWrapper = new QueryWrapper<>();
        smsUserRoleRelationQueryWrapper.lambda().eq(SmsUserRoleRelation::getUserId,userId);
        List<SmsUserRoleRelation> smsUserRoleRelation = smsUserRoleRelationMapper.selectList(smsUserRoleRelationQueryWrapper);
        List<String> roleIds = new ArrayList<>();
        for (SmsUserRoleRelation userRoleRelation : smsUserRoleRelation) {
            String roleId = userRoleRelation.getRoleId();
            roleIds.add(roleId);
        }
        if(!roleIds.contains("4")){
            return CommonResult.failed(CommonCodeEnum.LEAVE_ALLOW_NOT_OWN_CLASS);
        }
        Page<SmsWalkThrough> page = new Page<>(pageNum, pageSize);
        //查数据库中的数据
        QueryWrapper<SmsWalkThrough> walkThroughQueryWrapper = new QueryWrapper<>();
        walkThroughQueryWrapper.lambda().orderByDesc(SmsWalkThrough::getApplicationTime);
        smsWalkThroughMapper.selectPage(page,walkThroughQueryWrapper);
        List<SmsWalkThrough> smsWalkThroughs = page.getRecords();
        if(smsWalkThroughs == null){
            return CommonResult.failed(CommonCodeEnum.WALK_THOUGH_NOT_EXIST);
        }
        List<SmsWalkThroughAuditListVo> smsWalkThroughAuditListVos = new ArrayList<>();
        for(SmsWalkThrough smsWalkThroughAuditListVo : smsWalkThroughs){
            SmsWalkThroughAuditListVo smsWalkThroughAuditListVo1 = new SmsWalkThroughAuditListVo();
            BeanUtils.copyProperties(smsWalkThroughAuditListVo,smsWalkThroughAuditListVo1);
            smsWalkThroughAuditListVos.add(smsWalkThroughAuditListVo1);
        }
        int total = (int) page.getTotal();
        return CommonResult.success(smsWalkThroughAuditListVos,total);
    }
}
